package cn.zhx.trigger.listener;

import cn.zhx.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import cn.zhx.domain.strategy.service.IRaffleStock;
import cn.zhx.types.event.BaseEvent;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: zhx
 * @Date: 2024/07/15
 * @Description: 策略奖品库存为0
 **/
@Slf4j
@Component
public class StrategyAwardStockZeroCustomer {

    @Value("${spring.rabbitmq.topic.strategy_award_stock_zero}")
    private String topic;

    @Resource
    private IRaffleStock raffleStock;

    @RabbitListener(queuesToDeclare = @Queue(value = "strategy_award_stock_zero"))
    public void listener(String message) {
        try{
//            log.info("监听策略奖品库存消耗为0消息 topic: {} message: {}", topic, message);
            // 转换对象
            BaseEvent.EventMessage<StrategyAwardStockKeyVO> eventMessage = JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<StrategyAwardStockKeyVO>>() {}.getType());
            StrategyAwardStockKeyVO strategyAwardStockKeyVO = eventMessage.getData();
            //清空队列
            raffleStock.clearQueueValue();
            //清空库存
            raffleStock.clearStrategyAwardStock(strategyAwardStockKeyVO.getStrategyId(), strategyAwardStockKeyVO.getAwardId());
        }catch (Exception e){
            log.error("监听策略奖品库存消耗为0消息，消费失败 topic: {} message: {}", topic, message);
            throw e;
        }
    }
}
